let pathPrefix = "";
const fileAliases = {};

/*
 * Set a relative path prefix
 */
export function setPathPrefix(prefix) {
  pathPrefix = prefix;
}

export function getPathPrefix() {
  return pathPrefix;
}

// Note: addAliases are an experimental export,
export function addAliases(aliases) {
  Object.assign(fileAliases, aliases);
}

export function resolvePath(filename) {
  for (const alias in fileAliases) {
    if (filename.startsWith(alias)) {
      const replacement = fileAliases[alias];
      filename = filename.replace(alias, replacement);
    }
  }
  if (!filename.startsWith("http://") && !filename.startsWith("https://")) {
    filename = `${pathPrefix}${filename}`;
  }
  return filename;
}
/***
 * a/b/c, n/m => a/b/n/m
 */
export function relativePath(baseUrl, newPath) {
  let fPath = baseUrl.replace(/[^\/]+$/, "");
  return join(fPath, newPath);
}

// Beginning of a minimal implementation of the Node.js path API, that doesn"t pull in big polyfills.
export function dirname(url) {
  const slashIndex = url && url.lastIndexOf("/");
  return slashIndex >= 0 ? url.substr(0, slashIndex) : "";
}

export function join(...parts) {
  const separator = "/";
  parts = parts.map((part, index) => {
    if (index) {
      part = part.replace(new RegExp(`^${separator}`), "");
      part = part.replace(new RegExp(`^.${separator}`), "");
    }
    if (index !== parts.length - 1) {
      part = part.replace(new RegExp(`${separator}$`), "");
    }
    return part;
  });
  return parts.join(separator);
}
